# -*- coding: utf-8 -*-
import json
import logging.config
import threading
import time
from decimal import Decimal

from common.definition import CashMethod
from conf.config import BEANSTALKD_HOST, BEANSTALKD_PORT
from conf.logging import LOGGING_DICT_CONFIG
from helper.cash_helper import CashApplyHelper
from lib import beanstalkc
from lib.beanstalkc import DeadlineSoon

logger = logging.getLogger("execute_mq")
logging.config.dictConfig(LOGGING_DICT_CONFIG)
logging.getLogger("requests").setLevel(logging.ERROR)


class PayException(Exception):
    pass


def start():
    """

    :return:
    """

    try:
        logger.info("start cash apply server")
        logger.info("connect to beanstalk")
        bt = beanstalkc.Connection(host=BEANSTALKD_HOST, port=BEANSTALKD_PORT, connect_timeout=60)
        bt.watch("cash_apply")
        while True:
            job = bt.reserve(timeout=5)
            if job is None:
                continue
            try:
                logger.debug(job.body)
                body = json.loads(job.body)
                cash_method = int(body["cash_method"])
                open_id = body["open_id"]
                agency_uid = body["agency_uid"]
                fee = Decimal(body["fee"]).quantize(Decimal("0.00"))
                name = body["name"]
                ip = body["ip"]
                if cash_method not in [0, 2, 4]:
                    logger.error("不支持的提现方式")
                    job.delete()
                    continue
                if cash_method == CashMethod.BANK_CARD:
                    res = CashApplyHelper.deal_cash_bank_card(open_id, agency_uid, fee)
                elif cash_method == CashMethod.WECHAT:
                    if agency_uid:
                        # 合伙人收益提现
                        res = CashApplyHelper.deal_cash_wechat(open_id, agency_uid, fee, name)
                    else:
                        # 普通用户可提现余额提现
                        res = CashApplyHelper.deal_user_cash_wechat(open_id, fee, name)
                elif cash_method == CashMethod.BALANCE:
                    res = CashApplyHelper.deal_cash_balance(open_id, agency_uid, fee, ip)

                logger.info(res)
                job.delete()
            except Exception as e:
                logger.exception(e)
                logger.info("jid=%s，state=%s" % (job.jid, job.stats()['state']))
                job.release(delay=60)
    except Exception as e:
        if not isinstance(e, DeadlineSoon):
            logger.exception(e)
        time.sleep(1)
        logger.info("restart ...")
        start()


class CashApply(threading.Thread):
    def run(self):
        logger.info("start cash apply thread!")
        start()


if __name__ == "__main__":
    CashApply().run()
